﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Threading;
using System.ComponentModel;
using System.Speech.Recognition;
using System.ServiceModel;

namespace Loader
{

    public partial class MainWindow : Window
    {
        # region speech

        private SpeechRecognitionEngine _recognizer;
        private bool login = false;

        void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            foreach (RecognizedWordUnit word in e.Result.Words)
            {
                switch (word.Text)
                {
                    case "login":
                        if (login == false)
                        {
                            login = true;
                            tbxUser.Text = "sunny@live.com";
                            tbxPass.Password = "test";
                            btnlogin_Click(btnlogin, null);
                        }
                        break;
                    //case "now":
                    //    label1.Content = "now";
                    //    break;
                    //case "top":
                    //    label1.Content = "top";
                    //    break;
                    //case "down":
                    //    label1.Content = "down";
                    //    break;
                    default:
                        break;
                }
            }
            //throw new NotImplementedException();
        }

        void recongizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            //label1.Content = e.Result.Text;
            //MessageBox.Show("you said:" + e.Result.Text);
            //throw new NotImplementedException();
        }

        #endregion

        public MainWindow()
        {
            InitializeComponent();
            tbxUser.Focus();
            # region speech
            //login = false;
            //_recognizer = new SpeechRecognitionEngine();
            //_recognizer.SetInputToDefaultAudioDevice();

            //// Specify the exact words that the engine will try to recognize.
            //Choices choices = new Choices("login");

            //// Create and load a Grammar using the Choices above.
            //GrammarBuilder grBuilder = new GrammarBuilder(choices);
            //Grammar grammar = new Grammar(grBuilder);
            //_recognizer.LoadGrammar(grammar);

            //// Create the event handler
            //_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recognizer_SpeechRecognized);

            //// Start speech recognition
            //// RecognizeMode.Single: The recognition process will stop after the first recognition.
            //// RecognizeMode.Multiple: The recognition process will not stop after the first recognition.
            //_recognizer.RecognizeAsync(RecognizeMode.Multiple);

            #endregion
            _backgroundWorker.WorkerSupportsCancellation = true;
        }

        string docname = "";
        Storyboard loading1;
        string username;
        string password;
        Window2 win;
        BackgroundWorker _backgroundWorker = new BackgroundWorker();
        private void btnlogin_Click(object sender, RoutedEventArgs e)
        {
            //start loading
            gridLoading.Visibility = Visibility.Visible;
            loading1 = (Storyboard)FindResource("loading");
            loading1.RepeatBehavior = RepeatBehavior.Forever;
            loading1.Begin();

            username = tbxUser.Text;
            password = tbxPass.Password;

            btnlogin.IsEnabled = false;
            // Set up the Background Worker Events
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;
            _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;

            // Run the Background Worker
            _backgroundWorker.RunWorkerAsync(5000);

        }
        bool ok = false;
        // Worker Method
        void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ServiceReference2.Service1Client svc = new ServiceReference2.Service1Client();
            ok = true;
            try
            {
                try
                {
                    docname = svc.login(username, password);
                }
                catch (Exception)
                { }
                if (docname != "")
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        win = new Window2(docname, this);
                    }));
                }
                else
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        gridLoading.Visibility = Visibility.Collapsed;
                        lblerr.Visibility = Visibility.Visible;
                        loading1.Stop();
                        lblerr.Content = "Username/Password is wrong!";
                        tbxPass.Password = "";
                        login = false;
                    }));

                }
            }
            catch (NullReferenceException)
            {
                ok = false;
                MessageBox.Show("Error! Please check your internet connectivity.");
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    gridLoading.Visibility = Visibility.Collapsed;
                    lblerr.Visibility = Visibility.Visible;
                    loading1.Stop();
                    tbxPass.Password = "";
                    login = false;
                }));
            }
            finally
            {
                svc.Close();
            }

        }
       
        // Completed Method
        void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (ok == true)
            {
                if (e.Error != null)
                {
                    MessageBox.Show("Error! Please check your internet connectivity.");
                    login = false;
                }
                else if (docname != "" || docname == null)
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        //this.Hide();
                        win.Show();
                        this.Close();
                      
                    }));

                }

            }
        }

        private void tbxPass_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnlogin_Click(btnlogin, null);
            }
        }

        public void stopLoading()
        {
            gridLoading.Visibility = Visibility.Collapsed;
            win.Show();
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _backgroundWorker.CancelAsync();
            Application.Current.Shutdown();
        }

       

    }
}
